from django.utils import timezone
from rest_framework import serializers
from captcha.models import CaptchaStore
from captcha.conf import settings as captcha_settings
from .models import AdminUser
from zmad.models import ZTPUserCas


class CaptchaSerializer(serializers.Serializer):
    key = serializers.CharField()
    response = serializers.CharField(error_messages={
        'required': '请填写验证码。',
        'invalid': '请填写正确的验证码。'
    })

    def validate(self, attrs):
        key = attrs['key']
        response = attrs['response'].strip().lower()

        if not captcha_settings.CAPTCHA_GET_FROM_POOL:
            CaptchaStore.remove_expired()
        if captcha_settings.CAPTCHA_TEST_MODE and response.lower() == 'passed':
            # automatically pass the test
            try:
                # try to delete the captcha based on its hash
                CaptchaStore.objects.get(hashkey=key).delete()
            except CaptchaStore.DoesNotExist:
                # ignore errors
                pass
        elif not self.required and not response:
            pass
        else:
            try:
                CaptchaStore.objects.get(response=response, hashkey=key, expiration__gt=timezone.now()).delete()
            except CaptchaStore.DoesNotExist:
                raise serializers.ValidationError({'response': '请填写正确的验证码。'})
        return response


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=256, write_only=True, required=True)
    password = serializers.CharField(max_length=256, write_only=True, required=True)


class AdminUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdminUser
        fields = ('username', 'admin_level', 'is_active')
        read_only_fields = ('username', 'admin_level', 'is_active')


class ResetPasswordSerializer(serializers.Serializer):
    password_field = AdminUser._meta.get_field('password')
    current_password = serializers.CharField(
        max_length=password_field.max_length,
        write_only=True,
    )
    new_password = serializers.CharField(
        max_length=password_field.max_length,
        write_only=True,
        validators=password_field.validators
    )

    def validate_current_password(self, raw_password):
        if not self.instance.check_password(raw_password):
            raise serializers.ValidationError('密码不正确，请再试一次。')

    def update(self, instance, validated_data):
        new_password = validated_data['new_password']
        # 安全管理员需要修改对应用户账号的密码
        if instance.admin_level == AdminUser.STRATEGY_ADMIN:
            user = instance.related_user
            user.set_password(new_password)
            user.save()
            # 同步到cas_user中
            ZTPUserCas.objects.filter(username=user.username).update(password=user.password)
        instance.set_password(new_password)
        instance.save()
        return instance
